package p2p;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

import jhttpp2.Jhttpp2HTTPSession;
import jhttpp2.Jhttpp2Read;

public class P2pClientThread implements Runnable {
	public static int ECHOPORT = 10001;
	public static final int NUM_THREADS = 2;
	
	public static HashMap<String, PeerInfo> peerhm;
	public static HashMap<String, Integer> urlwait;
	public static HashMap<String, Integer> urlwriting;
	ServerSocket servSock;
	
	public P2pClientThread(int echoport2, int numThreads) {
		// TODO Auto-generated constructor stub
		peerhm = new HashMap<String, PeerInfo>();
		peerhm.clear();	
		
		urlwait = new HashMap<String, Integer>();
		urlwait.clear();
		
		urlwriting = new HashMap<String, Integer>();
		urlwriting.clear();
		
//		String hashurl = Jhttpp2Read.hashString("http://www.haivl.com/");
//		P2pClientThread.urlwait.put(hashurl, 1);
		
		//read config client p2p
		try {
			BufferedReader brc = new BufferedReader(new FileReader(new File("conf/p2pclient.p2pconf")));
			ECHOPORT = Integer.parseInt(brc.readLine());
			brc.close();
			System.out.println("Conf p2pclient: ip:" + String.valueOf(ECHOPORT));
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
				
        try {
            servSock = new ServerSocket(ECHOPORT);
        } catch(IOException e) {
            /* Crash the server if IO fails. Something bad has happened */
            throw new RuntimeException("Could not create ServerSocket " + e);

        }
        
        //set up server p2p control conf
        try {
			BufferedReader brc = new BufferedReader(new FileReader(new File("conf/p2pcontrolserver.p2pconf")));
			ControlHandler.P2PControlHost = brc.readLine();
			ControlHandler.p2PControlPort = Integer.parseInt(brc.readLine());
			brc.close();
			
			System.out.println("Conf p2pserver: " + ControlHandler.P2PControlHost + ":" + String.valueOf(ControlHandler.p2PControlPort));
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
     // Create a series of threads and start them.
//        for (int i=0; i<numThreads; i++) {
//            new ControlHandler(servSock, i).start();
//        }
        
      //check uuid exist
        if( ControlHandler.myUuid == "" ) {
			String filename =  "uuid.p2pconf";
	        String directory = "conf/";
	        
	    	//return size of file. if have file and size > 0 oke read cache
	        long findLong =  Jhttpp2Read.findFile(filename,new File(directory));
	        
	        //if uuid exit update infor to server
	        if( findLong > 0 ) {
	        	try {
					BufferedReader br = new BufferedReader(new FileReader(new File("conf/uuid.p2pconf")));
					String uuid = br.readLine();
					int uuidStrIndex = uuid.indexOf("UUID:");
					uuid = uuid.substring(uuidStrIndex + 5);
					ControlHandler.myUuid = uuid;
	//				System.out.println(uuid);
					
					Socket sock = new Socket(ControlHandler.P2PControlHost, ControlHandler.p2PControlPort);
					PrintWriter os = new PrintWriter(sock.getOutputStream( ), true);
					BufferedReader is = new BufferedReader(new InputStreamReader(sock.getInputStream()));
	
					String mesg = "UPDATE_INFO";
					os.print( mesg + "\r\n");
					os.flush();
					os.print( uuid + "\r\n");
					os.flush();
					os.print( String.valueOf(P2pClientThread.ECHOPORT) + "\r\n");
					os.flush();
					System.out.println("Sent \"" + mesg  + "\"");
					
					String reply = is.readLine( );
		            System.out.println("Got  \"" + reply + "\"");
		            br.close();
		            sock.close();
	        	} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	        } else {
	        	//uuid not exist, request new info
				try {
					Socket sock = new Socket(ControlHandler.P2PControlHost, ControlHandler.p2PControlPort);
					PrintWriter os = new PrintWriter(sock.getOutputStream( ), true);
					BufferedReader is = new BufferedReader(new InputStreamReader(sock.getInputStream()));
	
					String mesg = "REQUEST_ID";
					os.print( mesg + "\r\n");
					os.flush();
					//os.print( "b2028d64-0579-4461-8e22-6372b331af9f\r\n");
					//os.flush();
					os.print( String.valueOf(P2pClientThread.ECHOPORT) + "\r\n");
					os.flush();
					System.out.println("Sent \"" + mesg  + "\"");
					
					String reply = is.readLine( );
		            System.out.println("Got  \"" + reply + "\"");
		            
		            String uuid = reply;
		            int uuidStrIndex = uuid.indexOf("UUID:");
					uuid = uuid.substring(uuidStrIndex + 5);
					ControlHandler.myUuid = uuid;
		            
		            PrintWriter fpw = new PrintWriter(new File("conf/uuid.p2pconf"));
		            fpw.write(reply + "\r\n");
		            fpw.close();
		            sock.close();
		            
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	        }
	        
	        //get friend list
	        Socket sock;
			try {
				sock = new Socket(ControlHandler.P2PControlHost, ControlHandler.p2PControlPort);
				PrintWriter os = new PrintWriter(sock.getOutputStream( ), true);
				BufferedReader is = new BufferedReader(new InputStreamReader(sock.getInputStream()));
	
				String mesg = "REQUEST_FRIEND_LIST";
				os.print( mesg + "\r\n");
				os.flush();
				System.out.println("Sent \"" + mesg  + "\"");
				
				String reply = is.readLine( );
		        System.out.println("Got  \"" + reply + "\"");
		        
		        String uuid = "";
		        while( (uuid = is.readLine()) != null ) {
//		        	System.out.println("read uuid");
	        		String ip = is.readLine();
	        		String port = is.readLine();
	        		PeerInfo newPeerInfo = new PeerInfo();
	        		
	        		int uuidIndex = uuid.indexOf("UUID=");
	        		int ipIndex = ip.indexOf("IP=");
	        		int portIndex = port.indexOf("PORT=");
	        		
	        		newPeerInfo.uuid = uuid.substring(uuidIndex + 5);
	        		newPeerInfo.ip = ip.substring(ipIndex + 3);
	        		newPeerInfo.port = port.substring(portIndex + 5);
	        		
//	        		System.out.println("ADD FRIEND:" + newPeerInfo.ip);
	        		
	        		P2pClientThread.peerhm.put(newPeerInfo.uuid, newPeerInfo);
		        }
		        
		        P2pClientThread.peerhm.remove(ControlHandler.myUuid);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
	}
	
	public void run() {
		try {
			System.out.println("P2P Client Thread running. Port: " + P2pClientThread.ECHOPORT);
			while(true) {
				//create new seson to handle accept
				Socket client = servSock.accept();
//				System.out.println("Accept");
				new ControlHandler(client).start();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
